"use client";
import React, { useEffect, useState } from "react";
import { Table, Button, Modal, Form, Input, message, Space } from "antd";
import {
  articleControllerFindAllArticle,
  articleControllerCreateArticle,
  articleControllerUpdate,
  articleControllerRemove,
} from "@/app/servers/api/article";
import { PlusOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons";
import dynamic from "next/dynamic";
const CustomerWangEditor = dynamic(() => import("@/app/components/customer-wangEditor/customer-wangEditor"), { ssr: false });

const ArticleManage: React.FC = () => {
  const [articles, setArticles] = useState<API.Article[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState<number | null>(null);

  // 获取文章列表
  const fetchArticles = async () => {
    try {
      const { data } = await articleControllerFindAllArticle();
      setArticles(data);
    } catch {
      message.error("获取文章列表失败");
    }
  };

  useEffect(() => {
    fetchArticles();
  }, []);

  // 表格列定义
  const columns = [
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "内容",
      dataIndex: "content",
      key: "content",
      ellipsis: true,
    },
    {
      title: "操作",
      key: "action",
      render: (_: undefined, record: API.Article) => (
        <Space>
          <Button
            type="primary"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="primary"
            danger
            icon={<DeleteOutlined />}
            onClick={() => {
              Modal.confirm({
                title: "确认删除",
                content: "确定要删除这篇文章吗？",
                onOk: () => handleDelete(record.id),
              });
            }}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 处理新增/编辑表单提交
  const handleSubmit = async (values: API.Article) => {
    try {
      if (editingId) {
        await articleControllerUpdate(
          { id: editingId.toString() },
          { title: values.title, content: values.content }
        );
        message.success("更新文章成功");
      } else {
        await articleControllerCreateArticle({
          title: values.title,
          content: values.content,
        });
        message.success("创建文章成功");
      }
      setIsModalVisible(false);
      form.resetFields();
      setEditingId(null);
      fetchArticles();
    } catch {
      message.error("操作失败");
    }
  };

  // 打开编辑模态框
  const handleEdit = (record: API.Article) => {
    setEditingId(record.id);
    form.setFieldsValue({
      title: record.title,
      content: record.content,
    });
    setIsModalVisible(true);
  };

  // 打开新增模态框
  const handleAdd = () => {
    setEditingId(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  // 在 ArticleManage 组件内添加删除处理函数
  const handleDelete = async (id: number) => {
    try {
      await articleControllerRemove({ id: id.toString() });
      message.success("删除文章成功");
      fetchArticles();
    } catch {
      message.error("删除失败");
    }
  };

  return (
    <div className="p-6">
      <div className="mb-4">
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
          新增文章
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={articles}
        rowKey="id"
        pagination={{ pageSize: 10 }}
      />

      <Modal
        title={editingId ? "编辑文章" : "新增文章"}
        open={isModalVisible}
        onCancel={() => {
          setIsModalVisible(false);
          form.resetFields();
          setEditingId(null);
        }}
        width={800}
        footer={null}
      >
        <Form form={form} onFinish={handleSubmit} layout="vertical">
          <Form.Item
            name="title"
            label="标题"
            rules={[{ required: true, message: "请输入文章标题" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="content"
            label="内容"
            rules={[{ required: true, message: "请输入文章内容" }]}
          >
            <CustomerWangEditor />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
              <Button
                onClick={() => {
                  setIsModalVisible(false);
                  form.resetFields();
                  setEditingId(null);
                }}
              >
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ArticleManage;
